#include "Precompile.h"
#include "SceneManager.h"

namespace Graphics{
	// Lua wrapper functions
	int SceneManager::addMesh_luaWrap(LuaPlus::LuaObject modelId){
		if(!modelId.IsInteger()){
			LOG_ERROR("Invalid parameter type.");
			assert(0);
			return -1;
		}
		
		int meshId = addEntity(MeshPtr(new Mesh(modelId.GetInteger())));
		m_luaStateMeshes[modelId.GetState()].insert(meshId);
		return meshId;
	}

	void SceneManager::removeMesh_luaWrap(LuaPlus::LuaObject meshId){
		if(!meshId.IsInteger()){
			LOG_ERROR("Invalid parameter type.");
			assert(0);
			return;
		}

		int mesh = meshId.GetInteger();
		std::map<LuaPlus::LuaState*,std::set<int>>::iterator itr;
		if((itr = m_luaStateMeshes.find(meshId.GetState())) != m_luaStateMeshes.end()){
			itr->second.erase(mesh);
		}

		removeEntity(mesh);
	}

	LuaPlus::LuaObject SceneManager::getMesh_luaWrap(LuaPlus::LuaObject meshId){
		LuaPlus::LuaObject object;
		if(!meshId.IsInteger()){
			LOG_ERROR("Invalid parameter value type.");
			assert(0);
			return object;
		}

		int mesh = meshId.GetInteger();
		MeshPtr meshPtr = boost::static_pointer_cast<Mesh>(getEntity(mesh));
		if(!meshPtr)
			meshPtr = MeshPtr(new Mesh(-1));

		LuaPlus::LuaState* state = meshId.GetState();
		object = state->BoxPointer(meshPtr.get());
		object.SetMetaTable(state->GetGlobal("MeshMetaTable"));

		return object;
	}

	void SceneManager::purgeLuaState(LuaPlus::LuaState* state){
		std::map<LuaPlus::LuaState*,std::set<int>>::iterator itr;
		std::set<int>::iterator sItr;
		if((itr = m_luaStateMeshes.find(state)) != m_luaStateMeshes.end()){
			sItr = itr->second.begin();
			while(sItr != itr->second.end()){
				removeEntity(*sItr);
				sItr++;
			}

			m_luaStateMeshes.erase(itr);
		}
	}
}